package com.cloud.controller;


import com.alibaba.fastjson.JSON;
import com.cloud.commons.constants.ConsumeConstant;
import com.cloud.model.ResultContemt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/websocket/{username}")
@Component
public class WebSocketService {

    private static final Logger LOG = LoggerFactory.getLogger(WebSocketService.class);
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketService> webSocketSet = new CopyOnWriteArraySet<WebSocketService>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;


    // 接收的username
    private String username = "";

    @OnOpen
    public void OnOpen(Session session,@PathParam("username") String username) {
        webSocketSet.forEach(webSocketService -> {
            if (webSocketService.username.equals(username)) {
                // 匹配到了
                webSocketSet.remove(webSocketService);
            }
        });
        this.username = username;
        this.session = session;
        webSocketSet.add(this);

        ResultContemt resultContemt = new ResultContemt();
        resultContemt.setCount(webSocketSet.size());
        resultContemt.setType(ConsumeConstant.USER_LOGIN);
        resultContemt.setUserType(username);

        webSocketSet.forEach(webSocketService -> {
            resultContemt.setUsername(webSocketService.username);
            try {
                webSocketService.session.getBasicRemote().sendText(JSON.toJSONString(resultContemt));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

    }

    @OnClose
    public void OnClose() {
        webSocketSet.remove(this);
        webSocketSet.forEach(webSocketService -> {
            ResultContemt resultContemt = new ResultContemt();
            resultContemt.setType(ConsumeConstant.USER_RETURN);
            resultContemt.setUsername(webSocketService.username);
            resultContemt.setCount(webSocketSet.size());
            resultContemt.setUserType(this.username);
            try {
                webSocketService.session.getBasicRemote().sendText(JSON.toJSONString(resultContemt));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    @OnMessage
    public void OnMessage(String userContent) {
        ResultContemt resultContemt = new ResultContemt();
        resultContemt.setUserType(username);
        resultContemt.setType(ConsumeConstant.USER_CONTENT);
        resultContemt.setContent(userContent);
        webSocketSet.forEach(webSocketService -> {
            resultContemt.setUsername(webSocketService.username);
            try {
                webSocketService.session.getBasicRemote().sendText(JSON.toJSONString(resultContemt));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

    }
}
